﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hanhud.Web.Publish;
using Hanhud.Web.UI;
using Hanhud.Security;
using System.Text;
using Hanhud.Utils;
using System.Web.UI.HtmlControls;

namespace Hanhud.Web.Pages.Secure
{
    public enum EAction
    {
        View = 1,
        Add = 2,
        Update = 4,
        Delete = 8
    }

    public partial class AddEditArticle : SitePage
    {
        protected EAction _action = EAction.Add;
        private CArticle _article = null;
        private string _returnUrl = null;

        public AddEditArticle()
            : base("Secure", "AddEditArticle")
        {
            Permission.BitValue = (int)EPermission.SelectAccess | (int)EPermission.InsertAccesss | (int)EPermission.UpdateAccess | (int)EPermission.DeleteAccess | (int)EPermission.ApproveAccess; 

            this.Init += new EventHandler(AddEditArticle_Init);
            this.Load += new EventHandler(AddEditArticle_Load);
            this.PreRender += new EventHandler(AddEditArticle_PreRender);
        }

        void AddEditArticle_Init(object sender, EventArgs e)
        {
            if (CurrentUser == null)
            {
                // Chuyen nguoi dung den trang dang nhap
                Response.Redirect(string.Format("~/Membership/Login.aspx?returnUrl={0}", Server.UrlPathEncode(Page.ResolveUrl("~/Secure/AddEditArticle.aspx"))));
            }
        }

        void AddEditArticle_Load(object sender, EventArgs e)
        {
            try
            {
                _action = (EAction)Enum.Parse(typeof(EAction), Request.QueryString["act"], true);
            }
            catch
            {
                _action = EAction.Add;
            }

            if (_action == EAction.Add)
            {
                if (!UserPermission.InsertAccess)
                {
                    _article = new CArticle();
                }
                else
                {
                    // Nguoi dung ko co quyen insert
                    Response.Redirect(string.Format("~/Membership/Login.aspx?returnUrl={0}", Server.UrlPathEncode(Page.ResolveUrl("~/Secure/AddEditArticle.aspx"))));
                }
            }
            else if (_action == EAction.Update)
            {
                // Kiem tra quyen update cua user nay
                if (!UserPermission.UpdateAccess)
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["aid"]) && (_article = CArticle.GetArticle(Request.QueryString["pid"])) != null)
                    {
                        btnAddNew.Visible = false;
                        btnCancel.Visible = btnUpdate.Visible = true;
                    }
                }
                else
                {
                    // Nguoi dung ko co quyen update
                    Response.Redirect(string.Format("~/Membership/Login.aspx?returnUrl={0}", Server.UrlPathEncode(Page.ResolveUrl("~/Secure/AddEditArticle.aspx"))));
                }
            }

            if (!Page.IsCallback && !Page.IsPostBack)
            {
                BindCategoryList();
            }

            // Lay returnUrl
            _returnUrl = string.IsNullOrEmpty(Request.QueryString["returnUrl"]) ? Request.QueryString["returnUrl"] : string.Empty;
        }

        void AddEditArticle_PreRender(object sender, EventArgs e)
        {
            tbxTitle.Value = _article.Title;
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            string message = string.Empty;

            if (ValidInputData(ref message))
            {
                // Kiem tra lai xem user co' quyen insert ko ?
                if (!UserPermission.InsertAccess)
                {
                    // Nguoi dung ko co quyen update
                    Response.Redirect(string.Format("~/Membership/Login.aspx?returnUrl={0}", Server.UrlPathEncode(Page.ResolveUrl("~/Secure/AddEditArticle.aspx"))));
                }
                else
                {
                    // Luu lai tin tuc nay
                    int retv = CArticle.InsertArticle(
                        _article.CategoryId,
                        _article.Title,
                        _article.Abstract,
                        _article.ImageUrl,
                        _article.Body,
                        DateTime.Now,
                        DateTime.MaxValue,
                        UserPermission.ApproveAccess,
                        true,
                        false,
                        false);

                }
            }

            // Hien thi thong bao cho nguoi dung
            if (message.Length > 0)
            {
                CMessageBox.Show(Page, message);
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {

        }

        bool ValidInputData(ref string message)
        {
            bool bValid = true;
            StringBuilder sb = new StringBuilder();

            // Article's title
            _article.Title = CHelper.CleanHTML(tbxTitle.Value);
            if (string.IsNullOrEmpty(_article.Title))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Tiêu đề");
                bValid = false;
            }

            // Article's abstract
            _article.Abstract = CHelper.ConvertToHtml(CHelper.CleanHTML(tbxAbstract.Value));

            // Article's body
            _article.Body = tbxBody.Value.Trim();
            if (string.IsNullOrEmpty(_article.Body))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Nội dung");
                bValid = false;
            }

            message = sb.ToString();
            return bValid;
        }

        void BindCategoryList()
        {
            selArticleCategory.Items.Clear();
            selArticleCategory.SelectedIndex = -1;
            RecursiveBindCategory(0, CArticleCategory.BuildTree(), selArticleCategory);
        }

        void RecursiveBindCategory(int level, List<ICategory<int, CArticleCategory>> categoryTree, HtmlSelect sel)
        {
            string step = string.Empty;
            for (int i = 0; i < level; i++)
                step += "&nbsp;";

            foreach (ICategory<int, CArticleCategory> articleCategory in CArticleCategory.BuildTree())
            {
                sel.Items.Add(new ListItem(step + articleCategory.Title, articleCategory.CategoryID.ToString()));
                if (articleCategory.ChildCategories.Count > 0)
                    RecursiveBindCategory(level + 1, articleCategory.ChildCategories, sel);
            }
        }
    }
}